//  import java.io.BufferedReader;
//  import java.io.IOException;
//  import java.io.InputStreamReader;
//  import java.net.ServerSocket;
package tg1;

 import java.io.*;
 import java.net.*;
 import java.sql.*;
 import java.util.Map;
 import java.util.HashMap;

 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.channels.spi.*;
 import java.util.*;

 import tg1.JdbcDAO;
 import tg1.TrackerHttpUtils;
 import tg1.RequestHandler;

 public class Tracker {
 
	public static void main(String[] args) throws Exception{
         
		System.out.println("comecando o jaspionserver");    
		System.out.println("usando encodificacao UTF-8");    
	     
        	/*Declaro o ServerSocket, o Socket de comunicacao e declaro o leitor para a entrada de dados*/
		ServerSocket serv=null; 
		Socket s= null;
		BufferedReader entrada=null;
		FileWriter filewriter  =null;
	        PrintWriter log=null;

		int requestsProcessados=0;
		long tempoInicio=0;
		long diferencaTempo=0;
		long tempoTotal=0;
		int numReq=0;		

		RequestHandler requestHandler = new RequestHandler();
	
		try{ 
 			log = new PrintWriter( new FileWriter(new File("logsTempoTrackerMultiploCOMDns.txt")));
			/*um selector serve pra fazer I/O nao bloqueante */
			Selector acceptSelector = TrackerHttpUtils.getSelector();

			int keysAdded = 0;
			
			// Here's where everything happens. The select method will
			// return when any operations registered above have occurred, the
			// thread has been interrupted, etc.
			System.out.println("comecando a receber requests");
			//loop infinito xD
			while (1 == 1) {
				
				//DESABILITANDO REFRESH DO TRACKER PRA TESTAR NUMERO DE CONEXOES TRATADAS POR SEGUNDO
				//TrackerRefresher.refreshTrackerIfNeeded();
				
				keysAdded = acceptSelector.selectNow();
				if (keysAdded >0 ){
					
					// Someone is ready for I/O, get the ready keys
					Set readyKeys = acceptSelector.selectedKeys();
					Iterator i = readyKeys.iterator();
			
					// Walk through the ready keys collection and process date requests.
					while (i.hasNext()) {
						tempoInicio=System.currentTimeMillis();
						SelectionKey sk = (SelectionKey)i.next();
						i.remove();
	
						// The key indexes into the selector so you can retrieve the socket that's ready for I/O
						ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
						//log.print("recebi um request \n tempo em millis: " + tempoInicio);
						s = nextReady.accept().socket();
						
						//trackerUtils.sendTrackerResponse(s,requestHandler.handleRequest(s));
						TrackerHttpUtils.sendTrackerResponse(s,requestHandler.handleRequest(s));
						s.close();
						requestsProcessados++;
						numReq++;
						diferencaTempo=System.currentTimeMillis() - tempoInicio;
						tempoTotal+=diferencaTempo;
						if (tempoTotal> 1000){
							requestsProcessados++;
							log.println("requests por segundo"+requestsProcessados);
							requestsProcessados=0;	
						}
						log.println("terminei o request"+numReq+" \n tempo em millis: " +diferencaTempo);
						System.out.println("Request processado");
					}
				}
			}
			
			
         	}catch(Exception e){
         
			System.out.println("Algum problema ocorreu na main. Imprimindo stacktrace.");
	     		e.printStackTrace();
				TrackerHttpUtils.sendErrorResponse(s);
				s.close();
				serv.close();
		}
	}	
}
